package dao;

import java.io.InputStream;
import java.sql.*;

/**
 * @author DELL
 */
public class BaseDao {
    static {
        System.out.println("BaseDao static method has been call.");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("Success to lord driver!");
        } catch (ClassNotFoundException e) {
            System.out.println("Failed to lord driver");
        }
    }

    public static Connection getConnection() {
        // 创建数据库连接
        Connection c1 = null;
        try {
            c1 = DriverManager.getConnection(
                    "jdbc:mysql://localhost/online_shop", "jiang", "xiaojiang");
        } catch (SQLException throwables) {
            System.out.println("Failed to link database!");
        }
        return c1;
    }

    /**
     * 执行sql语句
     * 使用时要注意sql语句里问号和params位置的对应关系
     *
     * @param sql
     * @param params
     * @return 受影响的行数
     */
    public static int executedOperation(String sql, Object[] params) {
        int count = 0;
        Connection connection = getConnection();

        //准备SQL语句
        PreparedStatement ps = null;

        try {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i + 1, params[i]);
            }

            count = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeConnection(null, ps, connection);
        }

        return count;
    }

    public static void closeConnection(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {

        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
